import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_cloud_list_notifier.dart';

import 'package:casdon/modules/recipe/domain/states/recipe_cloud_list_state.dart';
import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class RecipeSmartScreen extends ConsumerWidget {
  const RecipeSmartScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(recipeCloudListNotifierProvider);
    final notifier = ref.watch(recipeCloudListNotifierProvider.notifier);
    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is ScrollEndNotification &&
            notification.metrics.pixels >=
                notification.metrics.maxScrollExtent - 50) {
          notifier.loadMore();
        }
        return false;
      },
      child: RefreshIndicator(
        onRefresh: () async {
          notifier.refresh();
        },
        child: CustomScrollView(
          slivers: [
            state.when(
              loading: () {
                // 如果是首次加载，显示 loading
                if (state.isLoading && state.value == null) {
                  return SliverToBoxAdapter(
                    child: Center(child: CommonLoadingWidget()),
                  );
                }
                // 如果有数据，直接显示数据（刷新时不显示 loading）
                if (state.value != null) {
                  return _buildContent(state.value!, ref);
                }
                return SliverToBoxAdapter(
                  child: Center(child: CommonLoadingWidget()),
                );
              },
              error: (e, _) => SliverToBoxAdapter(child: Text('')),
              data: (state) => SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  return _buildContent(state, ref);
                }, childCount: 1),
              ),
            ),

            state.when(
              loading: () => SliverToBoxAdapter(child: Text("......")),
              error: (e, _) => SliverToBoxAdapter(child: Text('')),
              data: (data) {
                if (data.data.isEmpty) {
                  return SliverToBoxAdapter(child: Text("暂无数据"));
                }
                final items = data.data[state.value!.selectedIndex];
                if (items.data.isEmpty) {
                  return SliverToBoxAdapter(child: Text("暂无数据"));
                }
                return SliverPadding(
                  padding: EdgeInsets.all(16.w),
                  sliver: SliverGrid(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      return GestureDetector(
                        onTap: () {
                          // 处理点击逻辑
                          _handleRecipeTap(
                            items.data[index],
                            data.isMiffyList[state.value!.selectedIndex],
                            context,
                            ref,
                          );
                        },
                        child: RecipeCardItem(item: items.data[index]),
                      );
                    }, childCount: items.data.length),
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 200.w,
                      mainAxisSpacing: 12.w,
                      crossAxisSpacing: 12.w,
                      mainAxisExtent: 144.h,
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent(RecipeCloudListState state, WidgetRef ref) {
    int selectedIndex = state.selectedIndex;
    return SizedBox(
      height: 100.h,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 15.h),
        itemCount: state.devList.length,
        itemBuilder: (context, index) {
          final item = state.devList[index];
          final isSelected = index == selectedIndex;

          return GestureDetector(
            onTap: () {
              // 调用选中设备的方法
              _onDeviceSelected(index, ref);
            },
            child: Container(
              margin: EdgeInsets.only(right: 12.w),
              width: MediaQuery.of(context).size.width / 2.5,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected
                      ? context.colorScheme.primary
                      : Colors.white, // 未选中状态使用灰色边框
                  width: isSelected ? 1.5 : 1.0,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Row(
                children: [
                  // 左侧文字区域
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Text(
                        item.name ?? '未知设备',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                          color: isSelected
                              ? context
                                    .colorScheme
                                    .primary // 选中状态文字颜色
                              : context.customColorThemeNonNull.textColor1,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),

                  // 右侧设备图片区域
                  Container(
                    width: 40,
                    height: 40,
                    margin: EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? context.colorScheme.primary.withOpacity(0.1)
                          : Colors.grey[100],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: item.iconUrl.isNotEmpty
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.network(
                              item.iconUrl,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return Icon(
                                  Icons.devices,
                                  color: isSelected
                                      ? context.colorScheme.primary
                                      : Colors.grey[400],
                                  size: 20,
                                );
                              },
                            ),
                          )
                        : Icon(
                            Icons.devices,
                            color: isSelected
                                ? context.colorScheme.primary
                                : Colors.grey[400],
                            size: 20,
                          ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // 设备选中处理方法
  void _onDeviceSelected(int index, WidgetRef ref) {
    ref.read(recipeCloudListNotifierProvider.notifier).selectDevice(index);
  }

  void _handleRecipeTap(
    RecipeCardData data,
    bool isMiffy,
    BuildContext context,
    WidgetRef ref,
  ) {
    final dev = ref
        .read(recipeCloudListNotifierProvider.notifier)
        .selectedDevice();
    if (dev == null) return;
    RecipeDetailRoute(
      recipeId: data.recipeId,
      devId: dev.devId,
      title: data.title,
      isSmart: data.isSmart,
      isMiffy: isMiffy,
    ).push(context);
  }
}
